# -*- coding: utf-8 -*-
import os
import thread
import time
import ctypes

from PyQt4.QtCore import QObject, SIGNAL, QString
from PyQt4.QtGui import QMessageBox, QIcon, QFileDialog

from config.preferences import SRC_PATH

try:
    _fromUtf8 = QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

from gpib.runnerUiVnaPlotter import RunnerUiVnaPlotter
from db.runnerUiAddDb import RunnerUiAddDb
from db.runnerUiSearchDb import RunnerUiSearchDb
from actions.actionsUploadDb import ActionsUploadDb
from db.runnerUiMenuAddProduto import RunnerUiMenuAddProduto
from db.runnerUiMenuEditarDb import RunnerUiMenuEditarDb
from images import images_rc


class ActionsUiMain(object):

    def __init__(self, uiMain, db, gpib):
        """
            Construtor da classe.
        """
        self.thread()
        self.uiMain = uiMain
        self.db = db
        self.gpib = gpib
        self.teste = 0
        self.connectSlots()
        self.modeloVna()



    def thread(self):
        """
            Metodo que cria uma thread para testar a conexao com a interface
            GPIB.
        """
        thread.start_new_thread( self.testeConexao,())



    def testeConexao(self):
        """
            Metodo para testar a conexao com o network.
        """
        try:
            self.gpib.connect('10.0.0.2')
            self.gpib.select(16)
            self.gpib.write("*CLS")
            self.teste = 1
        except:
            self.teste = 0



    def modeloVna(self):
        """
            Metodo para identificacao do modelo no network.
        """
        time.sleep(0.5)
        
        if self.teste == 1:
            self.gpib.connect('10.0.0.2')
            self.gpib.select( 16 )
            self.gpib.write("*CLS;")
            self.gpib.write("*IDN?")
            _modeloVna = self.gpib.read()
            self.gpib.write("*CLS;")
            modeloVnaShow = _modeloVna
            
            if _modeloVna == None:
                self.modeloVna = None
                self.uiMain.statusbar.showMessage(
                                                  _fromUtf8(
                                                  "Network desligado!"))
            
            else:
                _modeloVna = _modeloVna.split(",")
                modeloVna = _modeloVna[1]
                
                if modeloVna == "8712ET":
                    self.modeloVna = "8712ET"
                    self.uiMain.statusbar.showMessage(modeloVnaShow)
                    connectIcon = QIcon(":/vna-icon/searchDb.png")
                
                elif modeloVna == "8714C":
                    self.modeloVna = "8714C"
                    self.uiMain.statusbar.showMessage(modeloVnaShow)
                
                else:
                    self.modeloVna = ""
                    self.uiMain.statusbar.showMessage(
                                                      _fromUtf8(
                                                      "Network não conectado!"))
        else:
            self.uiMain.statusbar.showMessage(
                                              _fromUtf8(
                                              "Network não conectado!"))
        self.gpib.closeConnection()



    def connectSlots(self):
        """
            Metodo para conexao dos botoes da tela inicial.
        """
        QObject.connect(
                        self.uiMain.pushButtonCalibracao,
                        SIGNAL("clicked()"),
                        self.pushButtonCalibracaoClicked)
        QObject.connect(
                        self.uiMain.pushButtonVna,
                        SIGNAL("clicked()"),
                        self.pushButtonVnaClicked)
        QObject.connect(
                        self.uiMain.pushButtonDbUp,
                        SIGNAL("clicked()"),
                        self.pushButtonDbUpClicked)
        QObject.connect(
                        self.uiMain.pushButtonAddDb,
                        SIGNAL("clicked()"),
                        self.pushButtonAddDbClicked)
        QObject.connect(
                        self.uiMain.pushButtonDbSearch,
                        SIGNAL("clicked()"),
                        self.pushButtonDbSearchClicked)
        QObject.connect(
                        self.uiMain.actionAjuda,
                        SIGNAL("triggered()"),
                        self.actionsMenuAjuda)
        QObject.connect(
                        self.uiMain.actionSobre,
                        SIGNAL("triggered()"),
                        self.actionsMenuSobre)
        QObject.connect(
                        self.uiMain.actionAddProduto,
                        SIGNAL("triggered()"),
                        self.actionsMenuAddProduto)
        QObject.connect(
                        self.uiMain.actionEditarDb,
                        SIGNAL("triggered()"),
                        self.actionsMenuEditarDb)



    def actionsMenuAddProduto(self):
        """
        
        """
        self.MenuAddProduto = RunnerUiMenuAddProduto()
        self.MenuAddProduto.run()



    def actionsMenuEditarDb(self):
        """
        
        """
        self.uiMenuEditarDb = RunnerUiMenuEditarDb()
        self.uiMenuEditarDb.run()



    def actionsMenuAjuda(self):
        """
        
        """
        os.chdir(SRC_PATH + "/ajuda")
        QFileDialog.getOpenFileName()



    def actionsMenuSobre(self):
        """
        
        """
        QMessageBox.information(
                                None,
                                "TSM - VNA PLOTTER ",
                                "Fabio Berton")



    def pushButtonCalibracaoClicked(self):
        """
            Acao do botao Calibracao.
        """
        QMessageBox.information(
                                None,
                                "TSM - VNA PLOTTER ",
                                "Aplicativo em desenvolvimento :D")



    def pushButtonVnaClicked(self):
        """
            Acao do botao VNA PLOTTER.
            Instancia a classe RunnerVnaPlotter passando o modelo do network,
            variavel self.modeloVna, como argumento.
        """
        self.vnaPlotter = RunnerUiVnaPlotter(self.modeloVna)



    def pushButtonDbUpClicked(self):
        """
            Acao do botao Atualiza Banco de Dados.
            Instancia a classe ActionsUpdateDb e executa as funcoes.
        """
        self.uploadDb = ActionsUploadDb(self.db)
        self.uploadDb.copiarDadosParaDiretorioDbTmp()



    def pushButtonAddDbClicked(self):
        """
            Acao do botao Adicionar Dados ao Banco.
        """
        self.uiAddDb = RunnerUiAddDb()
        self.uiAddDb.run()



    def pushButtonDbSearchClicked(self):
        """
            Acao do botao Pesquisa Banco de Dados.
            Instancia a classe RunnerDataBase, onde estao todas as funcoes do
            banco de dados.
        """
        self.uiSearchDb = RunnerUiSearchDb()
        self.uiSearchDb.run()
